import {defineStore} from 'pinia'
import {GET_TOKEN, REMOVE_TOKEN, SET_TOKEN} from "@/utils/tokenUtil.ts";
import {getBlogUserInfoUrl, loginBlogUrl} from "@/api/login.ts";

interface UserStore {
    token: string,
    userInfo: {
        userName: '',
        nickName: '',
        avatar: '',
        email: '',
        phone: ''
    }
}

const useUserStore = defineStore('user', {

    state: (): UserStore => ({
        token: GET_TOKEN(),
        userInfo: null
    }),
    getters: {
        isLogin: (state) => state.token !== '' && state.token !== null && state.token !== undefined,
        getToken: (state) => state.token,
        getUserInfo: (state) => state.userInfo,
        getFirstWord: (state) => {
            const name = state.userInfo?.nickName || state.userInfo?.userName
            return name.substring(0, 1).toUpperCase()
        }
    },
    actions: {
        loginBlog(data) {
            return new Promise((resolve, reject) => {
                loginBlogUrl(data).then((res: any) => {
                    SET_TOKEN(res.token)
                    this.token = res.token
                    resolve(true)
                }).catch(err => {
                    reject(err)
                })
            })
        },
        getBlogUserInfo() {
            return new Promise((resolve, reject) => {
                getBlogUserInfoUrl().then((res: any) => {
                    this.userInfo = res.user
                    resolve(true)
                }).catch((err) => {
                    reject(err)
                })
            })
        },
        logOut() {
            return new Promise((resolve, reject) => {
                REMOVE_TOKEN()
                this.token = ''
                this.userInfo = null
                resolve(true)
            })
        }
    }


})


export default useUserStore
